<template>
  <div class="bgc-default" v-loading.fullscreen="listLoading" element-loading-text="加载中">
    <!-- 导航块 -->
    <div class="top-nav">
      <template v-for="(item, index) of topNavBar">
        <div :key="index" class="nav-item" :class="{'nav-active' : topNavBaroIndex === index}"
          @click="goTarget('#' + item.target, index)">{{item.name}}</div>
      </template>
    </div>
    <div class="content-box pad-l-20 pad-r-20 mar-t-20">

      <div class="comp">
        <div class="sub-title">商品分类</div>
        <div class="sub-form">
          <el-form label-position="right"
            label-suffix="："
            :label-width="formLabelWidth" 
          >
            <!-- 商品分类 -->
            <el-form-item label="商品分类" prop="title">
              <span>{{ thirdGoodsObj.thirdCategoryLabel }}</span>
              <el-button type="text" class="mar-l-20" @click="doChangeCategory">修改分类</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template v-if="baseDataPreFlag">

        <!-- 基本信息 -->
        <goods-info id="base-info"
          ref="goodsInfoRef"
          :thirdGoodsObj="thirdGoodsObj"
          :formLabelWidth="formLabelWidth"
          @addVaildShow="addVaildShow"
        >
        </goods-info>

        <!-- 平台基础属性 -->
        <platform-base-property id="platform-base-property"
          ref="platformBasePropertyRef"
          :propertyObj="thirdGoodsObj" 
          :formLabelWidth="formLabelWidth"
          @addVaildShow="addVaildShow"
        >
        </platform-base-property>

        <!-- 平台类目属性 -->
        <platform-category-property id="platform-category-property"
          ref="platformBaseCategoryPropertyRef"
          :propertyList="catePropertyList"
          :formLabelWidth="formLabelWidth"
        >
        </platform-category-property>
       
      </template>
    </div>

    <template v-if="validShowList.filter(item => item.validateMessage).length > 0">
      <div class="valid-show-box">
        <div class="box-head">错误信息（{{ validShowList.filter(item => item.validateMessage).length }}）</div>
        <div class="box-body">
          <el-row v-for="(item, index) in validShowList.filter(item => item.validateMessage)" :key="index" type="flex" align="middle">
            <template v-if="item.validateMessage">
              <el-col :span="16">
                <el-tooltip class="item" effect="light" :content="item.label + item.validateMessage" placement="top">
                  <div class="line-1">{{ index + 1 }}、{{ item.label }}{{ item.validateMessage }}</div>
                </el-tooltip>
              </el-col>
              <el-col :span="8" align="right">
                <el-button type="text" size="medium" class="font-red" @click="doJump(item.$el)">查看</el-button>
              </el-col>
            </template>
          </el-row>
        </div>
      </div>
    </template>

    <div class="bottom-bar">
      <el-button class="mar-l-30" type="primary" @click="doSave">保存</el-button>
    </div>

    <!-- 结果dialog -->
    <el-dialog :visible.sync="resultVisible"
      width="500px"
      top="15%"
      :center="true"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :show-close="false">

      <el-row type="flex">
        <el-col :span="4" align="center">
          <i class="el-icon-success font-green font-30"></i>
        </el-col>
        <el-col :span="18">
          <div><span class="font-22">保存成功</span></div>
          <div class="font-gray font-16 mar-t-10">
            <span>商品保存成功，数据已更新</span>
          </div>
        </el-col>
      </el-row>

      <!-- 底部按钮 -->
      <div class="mar-t-30" style="text-align: right">
        <el-button @click="doClose">关闭页面</el-button>
        <el-button @click="doSeeDetail">查看商品</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { getDictByGroupName } from '@/api/common/common'
  import { saveGoods, getGoodsDetail } from '@/api/goods/goods'
  import { getCateProperty } from '@/api/third/thirdGoods'

  import elDragDialog from '@/directive/el-dragDialog'
  import goodsInfo from './components/goods-info'
  import platformBaseProperty from './components/platform-base-property'
  import platformCategoryProperty from './components/platform-category-property'
  import goodsChannel from './components/goods-channel'
  import goodsSku from './components/goods-sku'
  import goodsOther from './components/goods-other'
  import goodsCommission from './components/goods-commission'
  import goodsParameter from './components/goods-parameter'

  export default {
    components: {
      goodsInfo,
      platformBaseProperty,
      platformCategoryProperty,
      goodsChannel,
      goodsSku,
      goodsOther,
      goodsCommission,
      goodsParameter
    },
    directives: {
      elDragDialog
    },
    props: {
      // 商品属性对象
      propertyObj: {
        type: Object,
        default() {
          return {
            platformType: '',
            thirdCategoryId: '',
            thirdCategoryLabel: ''
          }
        }
      }
    },
    watch: {
      propertyObj(val) {
        debugger
        console.log('11111')
      }
    },
    data() {
      return {
        // 基础数据准备flag
        baseDataPreFlag: false,
        // 表单文本宽度
        formLabelWidth: '240px',
        // 跳转源 30：零售 31：批发
        fromListPage: 30,
        // 商品对象
        thirdGoodsObj: {},
        // 验证列表
        validShowList: [],
        // 导航栏
        topNavBar: [
          { name: '基本信息', target: 'base-info' },
          { name: '平台基础属性', target: 'platform-base-property' },
          { name: '平台类目属性', target: 'platform-category-property' }
          // { name: '渠道设置', target: 'channel-set' },
          // { name: '规格信息', target: 'sku-set' },
          // { name: '商品佣金', target: 'commission-set' },
          // { name: '参数设置', target: 'params-set' },
          // { name: '商品详情', target: 'goods-detail' },
          // { name: '其他设置', target: 'other-set' }
        ],
        // 结果表单
        resultForm: {
          goodsId: ''
        },
        // 类目属性列表
        platformCatePropertyObj: {
          propertyRule: {
            properties: []
          },
          serviceRule: {},
          skuRule: {}
        },
        catePropertyList: [],
        // 导航位置
        topNavBaroIndex: 0,
        listLoading: false,
        resultVisible: false
      }
    },
    // 组件销毁
    beforeDestroy() {
      window.removeEventListener('mousewheel', this.getDomTop)
    },
    mounted() {
      Object.assign(this.thirdGoodsObj, this.propertyObj)
      this.initBaseData()
    },
    methods: {
      // 初始化基础信息
      initBaseData() {
        // 获取数据字典
        const getDictFx = new Promise((resolve, reject) => {
          this.$store.dispatch('setEnterpriseConfig', {})
          getDictByGroupName('ProjectGoodsDTO').then(response => {
            if (response.isError) {
              resolve(false)
            } else {
              this.$store.dispatch('setDict', response.data)
              resolve(true)
            }
          })
        })
        // 获取商品详情
        const goodsInfoFx = new Promise((resolve, reject) => {
          if (this.thirdGoodsObj.thirdGoodsId) {
            resolve(true)
            return
          }
          getGoodsDetail({ goodsId: this.thirdGoodsObj.goodsId }).then((response) => {
            if (response.isError) {
              resolve(false)
            } else {
              Object.assign(this.thirdGoodsObj, response.data)
              resolve(true)
            }
          })
        })

        const getCatePropertyFx = new Promise((resolve, reject) => {
          getCateProperty(this.thirdGoodsObj.platformType, this.thirdGoodsObj.shopId, this.thirdGoodsObj.thirdCategoryId).then(response => {
            if (response.isError) {
              resolve(false)
            } else {
              Object.assign(this.platformCatePropertyObj, response.data)
              if (this.platformCatePropertyObj.propertyRule) {
                this.catePropertyList = this.platformCatePropertyObj.propertyRule.properties.filter(item => item.propType === 10 || item.propType === 11)
                console.log('propertyType', this.platformCatePropertyObj.propertyRule.properties.map(item => item.propType))
              }
              console.log('getCateProperty', this.platformCatePropertyObj)
              resolve(true)
            }
          })
        })

        this.listLoading = true
        Promise.all([getDictFx, goodsInfoFx, getCatePropertyFx]).then((result) => {
          this.baseDataPreFlag = true
          const strArr = Object.values(result).filter(val => !val)
          // 存在调用异常
          if (strArr.length > 0) {
            this.$message({ type: 'error', message: '商品页异常' })
            this.listLoading = false
            return
          }

          this.$nextTick(function() {
            this.listLoading = false
            const queryParams = this.getCurrentPage().query
            if (queryParams.active) {
              this.goTarget(`#${this.topNavBar[queryParams.active]['target']}`, queryParams.active)
            }
            for (let i = 0; i < this.topNavBar.length; i++) {
              const dom = document.getElementById(`${this.topNavBar[i]['target']}`)
              this.$set(this.topNavBar[i], 'top', dom.offsetTop)
              this.$set(this.topNavBar[i], 'h', dom.clientHeight)
            }
          })

          // 监听
          const that = this
          window.addEventListener('mousewheel', that.getDomTop)
        })
      },
      // 鼠标滚动导航定位事件
      getDomTop() {
        const that = this
        const scroll = document.documentElement.scrollTop || document.body.scrollTop
        const windowHeight = document.documentElement.clientHeight || document.body.clientHeight
        const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
        for (let i = 0; i < that.topNavBar.length; i++) {
          const dom_id = `${that.topNavBar[i]['target']}`.trim()
          const dom_top = document.getElementById(dom_id).getBoundingClientRect().top
          if (dom_top < 250 && dom_top > 0) {
            that.topNavBaroIndex = i
          }
          if (scroll + windowHeight === scrollHeight) {
            that.topNavBaroIndex = that.topNavBar.length - 1
          }
        }
      },
      // 导航定位事件
      goTarget(id, index) {
        document.querySelector(id).scrollIntoView({
          behavior: 'smooth',
          block: 'center'
        })
        this.topNavBaroIndex = index
      },
      // 保存事件
      doSave() {
        this.validShowList = []
        const refArrays = []
        refArrays.push('goodsInfoRef')
        refArrays.push('platformBasePropertyRef')
        refArrays.push('platformBaseCategoryPropertyRef')
        // 表单校验
        const checkFailArrays = []
        refArrays.forEach(refKey => {
          const res = this.$refs[refKey].checkForm()
          if (!res) {
            checkFailArrays.push(refKey)
          }
        })
        if (checkFailArrays.length > 0) {
          return
        }

        // 表单组装
        const finalSubmitForm = {}
        refArrays.forEach(refKey => {
          const submitForm = this.$refs[refKey].submitForm()
          Object.assign(finalSubmitForm, submitForm)
        })
        console.log('setProperty success', finalSubmitForm)
      },
      // 保存后处理
      doSaveAfterHandle() {
        const refArrays = []
        refArrays.push('goodsInfoRef')
        refArrays.push('goodsChannelRef')
        refArrays.push('goodsSkuRef')
        refArrays.push('goodsCommissionRef')
        refArrays.push('goodsParameterRef')
        refArrays.push('goodsOtherRef')
        // 表单组装
        const finalSubmitForm = {}
        refArrays.forEach(refKey => {
          const submitForm = this.$refs[refKey].submitForm()
          Object.assign(finalSubmitForm, submitForm)
        })

        finalSubmitForm.enterpriseId = this.getEnterpriseId()
        finalSubmitForm.goodsId = this.goodsId

        this.listLoading = true
        saveGoods(finalSubmitForm).then((response) => {
          this.listLoading = false
          if (response.isError) return
          this.resultForm.goodsId = response.data
          this.resultVisible = true
        })
      },
      // 添加验证展示信息
      addVaildShow(field) {
        const propArr = this.validShowList.map(item => item.prop)
        if (propArr.indexOf(field.prop) === -1) {
          this.validShowList.push(field)
        }
      },
      // 修改分类事件
      doChangeCategory() {
        this.$confirm('修改分类将会使当前所编辑内容全部失效，确定要修改吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$emit('last')
        }).catch(() => {
        })
      },
      // 跳转
      doJump(element) {
        element.scrollIntoView({
          behavior: 'smooth',
          block: 'center'
        })
      },
      // 关闭页面事件
      doClose() {
        window.close()
      },
      // 查看商品事件
      doSeeDetail() {
        this.resultVisible = false
        this.$router.push({
          path: '/goods/edit/index',
          query: {
            goodsId: this.resultForm.goodsId,
            fromListPage: this.fromListPage,
            time: new Date().getTime()
          }
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .content-box {
    padding-bottom: 70px;
  }

  .top-nav {
    position: sticky;
    // top: 50px;
    top: 0;
    left: 0;
    width: 100%;
    height: 60px;
    background: white;
    display: flex;
    align-items: center;
    justify-content: space-around;
    z-index: 999;
    box-shadow: 0 2px 6px #eee;

    .nav-item {
      cursor: pointer;
    }

    .nav-active {
      position: relative;
      color: #409eff;

      &::after {
        content: '';
        position: absolute;
        bottom: -20px;
        left: -15px;
        width: calc(100% + 30px);
        height: 2px;
        background-color: #409eff;
      }
    }
  }

  // .bottom-bar {
  //   position: fixed;
  //   bottom: 0;
  //   left: 0;
  //   width: 100%;
  //   height: 72px;
  //   display: flex;
  //   align-items: center;
  //   justify-content: center;
  //   background: white;
  //   z-index: 999;
  //   box-shadow: 5px 1px 5px #cccccc;

  //   .el-button {
  //     width: 100px;
  //     height: 40px;
  //     line-height: 40px;
  //     padding: 0;
  //   }

  //   .el-button+.el-button {
  //     margin-left: 30px;
  //   }
  // }

  // .el-form-item__content {
  //   .el-button {
  //     padding: 0;
  //     height: 34px;
  //     width: 139px;
  //   }
  // }

  // .span-bar {
  //   padding: 0 50px;
  // }

  // .remove-btn {
  //   padding: 7px 6px !important;
  // }

  // .long-input {
  //   width: 80%;
  // }

  // .long-input-2 {
  //   width: 55%;
  //   margin-right: 5%;
  // }

  // .long-input-3 {
  //   width: 55%;
  // }

  // .short-input {
  //   width: 20%;
  // }

  // .short-input-2 {
  //   width: 25%;
  // }

  // .default-input {
  //   width: 50%;
  // }

  // .tips {
  //   color: gray;
  //   font-size: 12px;
  //   line-height: 1.2;
  //   padding-top: 5px;
  // }

  // .picture {
  //   width: 130px;
  //   height: 130px;
  //   display: block;
  // }

  // .pic-bar {
  //   position: relative;

  //   .close-icon {
  //     position: absolute;
  //     right: -30px;
  //     top: -11px;
  //     width: 31px;
  //     height: 40px;
  //     padding: 0 7px;
  //     cursor: pointer;
  //   }

  //   span {
  //     position: absolute;
  //     right: 0;
  //     bottom: 0;
  //     width: 100%;
  //     display: block;
  //     color: #fff;
  //     text-align: center;
  //     padding: 3px 0;
  //     background: rgba(0, 0, 0, 0.5);
  //     cursor: pointer;
  //   }
  // }

  .bottom-btn {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
  }
  .valid-show-box {
    position: fixed;
    top: 105px;
    right: 40px;
    width: 240px;
    border: solid 1px #E4E7ED;
    border-radius: 10px;
    background: white;
    overflow-y: auto;
    .box-head {
      background: lightgray;
      padding-left: 6px;
      font-weight: bold;
      height: 35px;
      padding-top: 7px;
      border-bottom: solid 1px #E4E7ED;
    }
    .box-body {
      max-height: 369px;
      overflow-y: auto;
      /deep/ .el-row {
        padding: 0 5px;
      }
      /deep/ .el-row:not(:last-child) {
        border-bottom: solid 1px #E4E7ED;
      }
      &::-webkit-scrollbar {
        width: 4px;
        height: 4px;
      }
      &::-webkit-scrollbar-thumb {
        border-radius: 5px;
        -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
        background: rgba(0,0,0,0.2);
      }
      &::-webkit-scrollbar-track {
        -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
        border-radius: 0;
        background: rgba(0,0,0,0.1);
      }
    }
  }
  /deep/ input[maxlength] {
    padding-right: 60px;
  }
  .content-box {
    .comp {
      display: flex;
      margin-bottom: 10px;
      /deep/ .sub-title {
        width: 7%;
        max-width: 160px;
        min-width: 140px;
        padding-top: 22px;
        background: white;
        margin-right: 20px;
        text-align: center;
        font-size: 16px;
        font-weight: bold;
      }
      /deep/ .sub-form {
        width: 100%;
        background: white;
        padding: 20px 50px 10px 0;
      }
    }
  }
</style>
